<?php

namespace app\admin\controller;

use app\common\ApiBase;
use app\common\ApiStatus;
use app\common\OsType;
use app\model\SystemAdmin;
use app\traits\Curd;
use support\Response;
use think\Exception;
use think\facade\Db;
use app\model\Tag as TagModel;

class Tag extends ApiBase
{
    use Curd;

    public function beforeAction()
    {
        if (empty(request()->admin_uid)) return $this->apiFailed('请先登录', ApiStatus::API_NEED_LOGIN->value);
        parent::beforeAction();
        $this->model      = new TagModel();
        $this->order_sort = 'sort asc,id asc';
        $this->params     = $this->buildTableParams(-1);
    }

    public function lists(): Response
    {
        list($page, $limit, $where) = $this->params;
        $where[] = ['status', '=', 1];
        $count   = $this->model->where($where)->count();
        $list    = $this->model->where($where)
            ->page($page, $limit)
            ->order($this->order_sort)
            ->select();
        $notes   = $this->model->notes ?? [];
        //管理员列表
        $notes['admin_user'] = (new SystemAdmin())->getAllAdminList();
        $notes['os_type']    = OsType::values();
        return json(['code' => ApiStatus::API_SUCCESS->value, 'msg' => 'success', 'data' => compact('count', 'list', 'notes')], JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
    }

    public function listsByHierarchy(): Response
    {
        list($page, $limit, $where) = $this->params;
        $where[] = ['status', '=', 1];
        $count   = $this->model->where($where)->count();
        $list    = $this->model->where($where)
            ->order($this->order_sort)
            ->select();

        $notes = $this->model->notes ?? [];
        return json(['code' => ApiStatus::API_SUCCESS->value, 'msg' => 'success', 'data' => compact('count', 'list', 'notes')], JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
    }

    public function add(): Response
    {
        $errorMessage = '';
        $post         = request()->post();
        if (isset($post['id'])) unset($post['id']);
        if (isset($post['uuid'])) unset($post['uuid']);
        if (isset($post['admin_os_type'])) unset($post['admin_os_type']);

        try {
            $post['create_time'] = time();
            $post['admin_uid']   = \request()->admin_uid ?? 0;
            $id                  = $this->model->insertGetId($post);
            $data['sort']        = $id * 66;
            $save                = $this->model->where('id', $id)->update($data);
        } catch (\Exception $e) {
            $errorMessage = $e->getMessage();
            $save         = false;
        }
        return json(['code' => ApiStatus::API_SUCCESS->value, 'msg' => $save ? '操作成功' : '操作失败:' . $errorMessage, 'data' => null], JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
    }

    public function edit(): Response
    {
        $errorMessage = '';
        $post         = \request()->post();
        $id           = $post['id'] ?? 0;
        $row          = $this->model->find($id);
        if (empty($row)) return json(['code' => ApiStatus::API_ERROR->value, 'msg' => '操作失败', 'data' => null], JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
        if (isset($post['id'])) unset($post['id']);

        try {
            $post['admin_uid'] = request()->admin_uid ?? 0;
            $post['u_time']    = myDate();
            $save              = $row->replace()->save($post);
            //全表重新排序
            if (isset($post['sort'])) {
                if ($post['sort'] < 20) {
                    $list = TagModel::getAllList([['status', '=', 0]], 'id,sort', 'sort asc');
                    foreach ($list as $value) {
                        $data = [
                            'sort'   => $value['sort'] * 66,
                            'u_time' => date('Y-m-d H:i:s'),
                        ];
                        TagModel::updateDataCache([['id', '=', $value['id']]], $data);
                    }
                }
            }
        } catch (Exception $e) {
            $errorMessage = $e->getMessage();
            $save         = false;
        }
        return json(['code' => ApiStatus::API_SUCCESS->value, 'msg' => $save ? '操作成功' : '操作失败:' . $errorMessage, 'data' => null], JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
    }

    public function delete(): Response
    {
        $post = \request()->post();
        $ids  = $post['ids'] ?? [0];
        if (is_string($ids)) $ids = json_decode($ids, true);
        $row = $this->model->whereIn('id', $ids)->select();
        if ($row->isEmpty()) return json(['code' => ApiStatus::API_ERROR->value, 'msg' => '删除数据不存在', 'data' => null], JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
        if (isset($post['id'])) unset($post['id']);

        $data = [
            'u_time' => myDate(),
            'status' => 2,
        ];
        $save = Db::table('tag')->whereIn('id', $ids)->update($data);

        return json(['code' => ApiStatus::API_SUCCESS->value, 'msg' => $save ? '操作成功' : '操作失败', 'data' => null], JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
    }
}